<template>
    <div id="recurrentManagement">
        <el-card class="box-card">
            <template #header>
                <div class="box_card_title">
                    <div class="left">
                        <el-button type="primary" @click="action = !action">新增</el-button>
                        <el-button type="primary">位置管理</el-button>
                    </div>
                    <div class="right">
                        <div class="input">
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-input v-model="inputValue" placeholder="名称"></el-input>
                                </el-col>
                                <el-col :span="12">
                                    <el-select v-model="selCon" class="m-2" placeholder="位置">
                                        <el-option v-for="item in locationData" :key="item.id" :label="item.locationName"
                                            :value="item.id" />
                                    </el-select>
                                </el-col>
                            </el-row>
                        </div>
                        <div class="button">
                            <el-button type="primary" @click="search" :icon="Search">查询</el-button>
                            <el-button :icon="RefreshLeft" @click="reset">重置</el-button>
                        </div>
                    </div>
                </div>
            </template>
            <el-table :data="tableData" stripe style="width: 100%" max-height="calc(100vh - 270px)"
                :row-style="{ height: '50px' }">
                <!-- 图片 -->
                <el-table-column prop="img" label="封面图">
                    <!-- 插槽图片(默认) -->
                    <template #default="scope">
                        <el-image style="height: 25px" :src="scope.row.img[0]?.imgName" :zoom-rate="1.2" :initial-index="4"
                            fit="cover" :preview-src-list="filterImg(scope.row.img)" />
                    </template>
                </el-table-column>
                <!-- 标题、城市 -->
                <el-table-column prop="carouselTitle" label="标题" />
                <el-table-column prop="sort" label="排序" />
                <el-table-column prop="location" label="位置" />
                <!-- 展览、创建时间 -->
                <el-table-column label="展览时间">
                    <template #default="scope">
                        {{ filterTime(scope.row.overTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="创建时间">
                    <template #default="scope">
                        {{ filterTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <!-- 操作按钮 -->
                        <el-row>
                            <el-col :span="8">
                                <el-text class="mx-1" type="primary" @click="change(scope.row)">编辑</el-text>
                            </el-col>
                            <el-col :span="8">
                                <el-text class="mx-1" type="danger" @click="deleteMethod(scope.row.id)">删除</el-text>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background layout="prev, pager, next, jumper" :total="total" v-model:current-page="currentPage1"
                :page-size="pageSize1" @current-change="handleCurrentChange"
                style="margin-top: 20px;float: right; height:30px;" />
        </el-card>
        <!-- 对话框 -->
        <!-- @close="() => formData = {}" -->
        <el-dialog v-model="action" :title="option ? '新增' : '修改'" width="30%" @close="clearValid">
            <!-- 定义对话框主题内容（表单） -->
            <el-form label-width="100px" :model="formData" style="max-width: 460px" :rules="rules" ref="ruleFormRef">
                <el-form-item label="图片">
                    <el-upload action="/dev-api/api/uploadimg/" list-type="picture-card" v-model:file-list="formData.img">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>

                </el-form-item>
                <el-form-item label="名称" prop="carouselTitle">
                    <el-input v-model="formData.carouselTitle" placeholder="输入内容" />
                </el-form-item>
                <el-form-item label="位置" prop="location">
                    <el-select fit-input-width v-model="formData.location" placeholder="选择选项">
                        <el-option label="请选择" value="" />
                        <el-option v-for="item in locationData" :key="item.id" :label="item.locationName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="formData.sort" placeholder="输入内容" />
                </el-form-item>
                <el-form-item label="开始时间" prop="createTime">
                    <el-date-picker v-model="formData.createTime" type="datetime" placeholder="开始时间" />
                </el-form-item>
                <el-form-item label="结束时间" prop="overTime">
                    <el-date-picker v-model="formData.overTime" type="datetime" placeholder="开始时间" />
                </el-form-item>
            </el-form>
            <!-- 定义对话框足部 -->
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="action = false">取消</el-button>
                    <el-button type="primary" @click="option ? addData(ruleFormRef) : updateData(ruleFormRef)">
                        保存
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import { ref, reactive, Fragment } from 'vue'
import moment from "moment"
import service from '@/utils/request'
import type { FormInstance, FormRules } from 'element-plus'
import {
    Search, RefreshLeft
} from '@element-plus/icons-vue'
const currentPage1 = ref(1)
const pageSize1 = ref(5)
const locationData = ref([])
const getLocation = async () => {
    const { data, code } = await service.get(`/api/curousel/showLocation/`)
    if (code == 200) {
        locationData.value = data
    }
}
const inputValue = ref('')
const total = ref(0)
const getDateList = async () => {
    const data: any = await service.get(`/api/curousel/showAddDelCurousel/?page=${currentPage1.value}&size=${pageSize1.value}&keyword=${inputValue.value}&location_id=${selCon.value}`)
    if (data.code == 200) {
        tableData.value = data.data
        total.value = data.total
    }
}
const search = () => {
    getDateList()
}
const handleCurrentChange = (val: any) => {
    currentPage1.value = val
    getDateList()
}
const reset = () => {
    inputValue.value = ''
    selCon.value = ''
    currentPage1.value = 1
    pageSize1.value = 5
    getDateList()
}

const success = (e: any) => {
    formData.img = [...formData['img'], e.path]
}
const deleteMethod = (id: any) => {
    ElMessageBox.confirm(
        '确定删除？此消息无法恢复',
        '删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const { code } = await service.delete(`/api/curousel/showAddDelCurousel/?id=${id}`)
            if (code !== 200) {
                return
            }
            getDateList()
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

// 对话框是否显示
let action = ref(false)
// 判断对话框是添加还是修改
let option = ref(true) //true 添加  false删除
// 选中的位置
const selCon = ref('')
// 列表遍历的数据
const tableData = ref([])
// 表单内容
let formData = reactive({
    img: [],
    carouselTitle: '',
    location: null,
    sort: 1,
    createTime: '',
    overTime: '',
    isDeleted: 0
})
// 定义表单ref
const ruleFormRef = ref<FormInstance>()
// 定义表单规则
const rules = reactive<FormRules>({
    carouselTitle: [
        { required: true, message: '请输入名称', trigger: 'blur' },
        { min: 3, max: 5, message: '长度3到5', trigger: 'blur' },
    ],
    sort: [
        { required: true, message: '请输入排序', trigger: 'blur' },
    ],
    location: [
        {
            required: true,
            message: '请选择位置',
            trigger: 'change',
        },
    ],
    createTime: [
        {
            type: 'date',
            required: true,
            message: '请选择时间',
            trigger: 'change',
        },
    ],
    overTime: [
        {
            type: 'date',
            required: true,
            message: '请选择时间',
            trigger: 'change',
        },
    ],
})
onMounted(() => {
    getLocation()
    getDateList()
})
// 添加数据
let addData = async (formEl: FormInstance | undefined) => {
    console.log(formEl, '=======');
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            let addObj = {
                img: formData.img.map(item => item.response.path),
                carouselTitle: formData.carouselTitle,
                location: formData.location,
                sort: formData.sort,
                createTime: filterTime(formData.createTime),
                overTime: filterTime(formData.overTime),
                isDeleted: 0
            }
            const data: any = await service.post('/api/curousel/showAddDelCurousel/', addObj)
            if (data.code == 200) {
                ElMessage(data.msg)
                action.value = false
                getDateList()
                formData.img = []
                formData.carouselTitle = ''
                formData.location = null
                formData.sort = 1
                formData.createTime = ''
                formData.overTime = ''
                formData.isDeleted = 0
                action.value = false
            } else {
                ElMessage('你所选参数有误！')
            }
        } else {
            console.log('123');
        }
    })

}
// 点击修改后操作
let change = (scope: any) => {
    option.value = false
    action.value = true
    formData = scope
    const arr = scope.img.map((item: any) => {
        return {
            name: item.imgName.slice(-10, -1),
            url: item.imgName,
        }
    })
    formData.img = arr
}
// 修改数据
let updateData = async (formEl: FormInstance) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const arr = formData.img.map(item => {
                if (item.response) {
                    return item.response.path
                } else {
                    return item.url
                }
            })
            const id = parseInt(formData.location) === formData.location ? formData.location : locationData.value.filter(item => {
                return item.locationName === formData.location
            })[0].id
            const editObj = {
                id: formData.id,
                carouselTitle: formData.carouselTitle,
                sort: formData.sort,
                location: id,
                createTime: filterTime(formData.createTime),
                overTime: filterTime(formData.overTime),
                img: arr
            }
            const { code, msg } = await service.post('/api/curousel/editCurousel/', editObj)
            if (code === 200) {
                action.value = false
                ElMessage(msg)
            } else {
                ElMessage('你所选参数有误！')
            }
            getDateList()
        }
    })


}
// 重置表單驗證
const clearValid = () => {
    ruleFormRef.value.resetFields()
}
//过滤图片
const filterImg = (list: any) => {
    return list.map((item: any) => item?.imgName)
}
// 过滤方法（格式化时间数据）
const filterTime = (time: any) => {
    return moment(time).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content {
    flex-direction: column;
    align-items: normal !important;
}

::v-deep .el-date-editor--datetime {
    width: 100%;
}

::v-deep .el-input__wrapper {
    width: 100% !important;
}

#recurrentManagement {
    height: calc(100vh - 84px);
    padding: 20px;

    .mx-1 {
        cursor: pointer;
    }


    .box-card {
        height: 100%;

        .el-button {
            width: 80px;
        }

        ::v-deep .el-card__header {
            border-bottom: 0px;
        }

        // 设置头部样式
        .box_card_title {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .right {
                display: flex;
                align-items: center;
                justify-content: space-between;
                width: 700px;

                .input {
                    .el-row {
                        display: flex;
                        align-items: center;
                    }
                }
            }
        }
    }
}

.el-form-item__content {
    width: 100% !important;
    background-color: red;
}

// 定义上传图片框~~~
.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    display: flex;
    flex-direction: column;
    font-size: 28px;
    color: #cccccc;
    background-color: #f9f9f9;
    width: 100px;
    height: 100px;
    text-align: center;
    font-weight: 900;

    span {
        font-size: 14px;
    }
}
</style>
<style>
.el-table .el-table__cell {
    z-index: auto !important;
}
</style>